package cn.wizzer.app.web.commons.ext.websocket.main.base;

import io.netty.channel.Channel;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 考虑再三还是加个缓存比较好-
 */
public class NettyCache {

    static private final ExpiringMap map = ExpiringMap.builder().variableExpiration()
            .expiration(24, TimeUnit.HOURS)
            .expirationPolicy(ExpirationPolicy.CREATED)
            .build();
    static private final Map<Channel, HashMap> localMap = new Hashtable();

    public static void init(Channel channel) {
        localMap.put(channel, new HashMap());
    }

    public static void destroy(Channel channel) {
        localMap.get(channel).clear();
        localMap.remove(channel);
    }

    public static Map<Channel, HashMap> getLocalMap() {
        return localMap;
    }

    public static ExpiringMap getMap() {
        return map;
    }

    public static <T> T localGet(Channel channel, Object key) {
        try {
            return (T) localMap.get(channel).get(key);
        } catch (Exception e) {
            return null;
        }
    }


    public static void localRemove(Channel channel, Object key) {
        localMap.get(channel).remove(key);
    }


    public static void localSet(Channel channel, Object key, Object value) {
        localMap.get(channel).put(key, value);
    }

    /**
     * 全局缓存
     *
     * @param key
     */
    public static void globalRemove(Object key) {
        map.remove(key);
    }

    /**
     * 全局缓存
     *
     * @param key
     * @param mills
     */
    public static void globalPut(Object key, Object value, long mills) {
        map.put(key, value, ExpirationPolicy.ACCESSED, mills, TimeUnit.MILLISECONDS);
    }

    public static void globalPut(Object key, Object value) {
        map.put(key, value);
    }

    public static void globalDel(Object key) {
        map.remove(key);
    }


    /**
     * 全局缓存
     *
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T globalGet(Object key) {
        try {
            return (T) map.get(key);
        } catch (Exception e) {
            return null;
        }
    }


}
